﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Client.XML
{
    public class XmlOperator
    {
        static XmlOperator()
        {
            xmlSerializer = new XmlSerializer(typeof(PlanList));
        }

        private static XmlSerializer xmlSerializer = null;
        /// <summary>
        /// 获取计划历史列表
        /// </summary>
        /// <returns></returns>
        public static PlanList GetPlanList(string pPath)
        {
            if (!File.Exists(pPath)) {
                File.Create(pPath);
            }
            StreamReader fs = new StreamReader(pPath);

            PlanList p = null;
            try
            {
                p = (PlanList)xmlSerializer.Deserialize(fs.BaseStream);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fs.Close();
            }

            return p;
        }

        /// <summary>
        /// 反序列化xml文件中的记录
        /// </summary>
        /// <param name="pPath"></param>
        /// <returns></returns>
        public static PlanList Deserialize(string pPath)
        {
            PlanList ret = new PlanList();

            StreamReader fs = new StreamReader(pPath);

            try
            {
                ret = (PlanList)xmlSerializer.Deserialize(fs.BaseStream);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                fs.Close();
            }

            return ret;
        }
        
        /// <summary>
        /// 序列化日志内容到xml文件中
        /// </summary>
        /// <param name="pPath"></param>
        /// <param name="pList"></param>
        public static void Serialize(string pPath, PlanList pList)
        {   
            StreamWriter sw = new StreamWriter(pPath);
            try
            {
                xmlSerializer.Serialize(sw.BaseStream, pList);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sw.Close();
            }
        }
    }
}
